package org.databandtech.logmock.rpc;

import java.nio.charset.Charset;
import java.util.Properties;

import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.api.RpcClient;
import org.apache.flume.api.SecureRpcClientFactory;
import org.apache.flume.event.EventBuilder;

public class SecureRpcClientFacade {

	private RpcClient client;
	  private Properties properties;

	  public void init(Properties properties) {
	    // Setup the RPC connection
	    this.properties = properties;
	    // Create the ThriftSecureRpcClient instance by using SecureRpcClientFactory
	    this.client = SecureRpcClientFactory.getThriftInstance(properties);
	  }

	  public void sendData(String data) {
	    // Create a Flume Event object that encapsulates the sample data
	    Event event = EventBuilder.withBody(data, Charset.forName("UTF-8"));

	    // Send the event
	    try {
	      client.append(event);
	    } catch (EventDeliveryException e) {
	      // clean up and recreate the client
	      client.close();
	      client = null;
	      client = SecureRpcClientFactory.getThriftInstance(properties);
	    }
	  }

	  public void cleanUp() {
	    // Close the RPC connection
	    client.close();
	  }
	}
